# -*- coding: utf-8 -*-

from common.order_inquiry.model import *
from common.utils import exceptions as err
from common.utils import track_logging
from common.utils.decorator import sql_wrapper

_LOGGER = track_logging.getLogger(__name__)


@sql_wrapper
def create(data):
    try:
        order_inquiry = OrderInquiry()
        order_inquiry.order_inquiry_no = data['order_inquiry_no']
        order_inquiry.mch_id = data['mch_id']
        order_inquiry.out_trade_no = data['out_trade_no']
        order_inquiry.service = data['service']
        order_inquiry.user_id = data['user_id']
        order_inquiry.username = data['username']
        order_inquiry.amount = data['amount']
        order_inquiry.transaction_time = data['transaction_time']
        order_inquiry.notify_url = data['notify_url']
        order_inquiry.mch_create_ip = data['mch_create_ip']
        order_inquiry.sign = data['sign']
        order_inquiry.receipt = data['receipt']
        order_inquiry.status = 0  # PENDING
        order_inquiry.reason_failure_id = None
        order_inquiry.notify_status = 0  # READY
        order_inquiry.notify_count = 0
        order_inquiry.inquiry_desc = data['desc']
        order_inquiry.save()
        return order_inquiry
    except Exception as e:
        _LOGGER.exception('create_order_inquiry error, %s', e)
        raise err.DataError()


@sql_wrapper
def get_order_inquiry_by_trade(out_trade_no):
    return OrderInquiry.query.filter(OrderInquiry.out_trade_no == out_trade_no).first()

@sql_wrapper
def get_order_inquiry(order_inquiry_no):
    return OrderInquiry.query.filter(OrderInquiry.order_inquiry_no == order_inquiry_no).first()

@sql_wrapper
def get_order_inquiry_by_mch(mch_id, order_inquiry_no, out_trade_no):
    return OrderInquiry.query.filter(OrderInquiry.mch_id == mch_id, OrderInquiry.order_inquiry_no == order_inquiry_no, OrderInquiry.out_trade_no == out_trade_no).first()
